<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**

https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/GcmEndpoints
http://api.shephertz.com/tutorial/Push-Notification-Android/
 * Controller to for user related information
 * 
 * THis is a copy of user controller
 * 
 * NOTE: If you update this section/class. please find a time to check the 
 *      User controller for any possible affected behavior.
 * 
 * Sample bench Marking
 *    $this->benchmark->mark('login_start'); 
 *    $this->benchmark->mark('login_end'); 
 *    $this->benchmark->elapsed_time('login_start', 'login_end');
 */
include_once __DIR__.'/user.php';
class Admin extends User{

    public function __construct() {
        parent::__construct();
        if ($this->acl_auth->logged_in())
            $this->acl_auth->restrict_access('admin');
            if($this->acl_auth->logged_in() && !$this->session->userdata("user_id")){
                // Annoying why theres user_id in session.
                // I will logout him then.
                $this->redirect('admin/logout');
            }
        
        $this->permission = 'admin';
        //log_message('error','SessionDATA: '.$this->session->userdata('session_id'));
    }
    
	public function index()
	{
        log_message('debug',print_r(get_class_methods($this->router), true));
        
        if ($this->acl_auth->logged_in()){
            // user already loggedin, put him to the appropriate page.
            if ($this->acl_auth->has_role('admin')){
                $this->redirect('lists'); // Admin must go to admin page.
            }else{
                redirect($this->acl_auth->get_config('landing_page'));
            }
        }
        
        $this->login();
	}
    
    
    /**
     * register
     */
    public function register()
    {

        $this->acl_auth->restrict_access('admin');
        $this->enableProfiler();
        
        
        if($this->isPost()){
            $this->load->library('configuration','configuration'); 
            if ((!$this->input->post("id")) && strlen($this->input->post("password"))<$this->configuration->getPasswordCharacterLimit()){
                $this->session->set_flashdata('error', "Password must atleast 8 characters.");
            }else{
                foreach ($_POST as $k=>$v){
                    $data[$k]=$v;
                }
                
                // Clear some params
                if (isset($data['submit'])) unset($data['submit']);
                unset($data['permission']);
                
                $data ['login']=0;
//                $data = array(
//                    'id' => $this->input->post("id"), 
//                    'store_name' => $this->input->post("store_name"), 
//                    'account_name' => $this->input->post("account_name"), 
//                    'email' => $this->input->post("email"),
//                    'password' => $this->input->post("password"),
//                    'lname' => $this->input->post("lname"), 
//                    'fname' => $this->input->post("fname"), 
//                    'status' => $this->input->post("status"), // TOBE added on Tables
//                    'login' => 0,
//                    //'logged_at' => 0, // timestamp
//                    //'logged' => ,
//                    //'timestamp' => time(), // timestamp
//                    //'extra_field' => 'value'
//                    );
    //            if ($data['id'] && !trim($data['password'])){
    //                log_message('info', 'user password is empty');
    //                unset($data['password']); // Empty Password.. Dont Update
    //            }
                log_message('error', print_r($data, true));
                $success = $this->acl_auth->register( $data, $this->input->post("permission"));
                if ($success){
                    log_message("info", "Success");
                    $messages = $this->acl_auth->messages();
                    $this->session->set_flashdata('success',  $messages[0]);

                }else{
                    log_message("info", "error");
                    $this->session->set_flashdata('datas',  json_encode($data));
                    $errors = $this->acl_auth->errors();
                    if ($errors){
                        //$this->session->set_flashdata('errors',  json_encode($this->acl_auth->errors()));
                        $this->session->set_flashdata('errors',  json_encode($this->acl_auth->errors()));
                        $this->session->set_flashdata('error',  $errors[0]);
                    }
                }
            }
            $this->redirect('lists');
        }
    }
    
    /**
     * Ability to unlock user by admin
     * Ajax call
     */
    public function unlockUser()
    {   
        $this->acl_auth->restrict_access('logged_in');

        //$id = $this->input->post('id');
        //$sid = $this->input->post('s_id');
        //$return = array('stat'=>-1, 'msg'=>'Failed.'."{'id':$id,'sid':$sid}");
        $return = array('stat'=>-1, 'msg'=>'Server Error.');
        
        if ($this->input->is_ajax_request()){
            // TODO, I to add message to audit trail
            $this->load->model('user_model');
            $id = $this->input->post('id');
            $sid = $this->input->post('s_id');
            try{
                $this->user_model->unlocked_user($id, $sid);
                $this->load->model('audit_model');
                $user = $this->user_model->get_by('id',$id);
                $account_name = ($user)?$user->account_name:'UNKNOWN USER('.$id.')';
                $this->audit_model->save(Audit_model::PROCESS, array(
                    'user'=>$this->session->userdata('user_id'),
                    'user_account'=>$this->session->userdata('user_account'),
                    'msg' => 'Unlock User - '.$account_name,
                ));
                $return['stat']=0;
                $return['msg']='Success.';
                
            }  catch (Exception $e){
                $return['msg']='Error unlocking user account.';
            }
        }
        
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($return));
        
    }
    
    /**
     * Test User If exist of not
     * 
     * @param str $user account_name in database
     */
    public function testuser(){
        $this->output->set_content_type('application/json');
        
       //echo '{"name":"'.$this->input->post('account_name').'"}';
        if (1){
            $this->load->model('user_model');
            $user = $this->user_model->get_user($this->input->post('account_name'));


            if ($user){ //user Exist
                $this->output->set_output('{"stat":-1}');
            }else{
                $this->output->set_output('{"stat":0}');
            }
        }
    }
    
    
    
    public function active_user(){
        $this->acl_auth->restrict_access('admin');

        //$this->output->enable_profiler(TRUE);
        //$config = array('config'  => FALSE,'queries' => TRUE);
        //$this->output->set_profiler_sections($config);
        
        $data['title']='Active Users';        
        $views['_tabs'] = 'user/tabs';
        $views['_header'] = 'user/header';
        $views['_content'] = 'user/activeuser';

//        $views['_tabs'] = 'user/tabs';
//        $views['_userform'] = 'user/user_form';
//        $views['_content'] = 'user/lists';

        $this->load->model('user_model');
        //$data['users']= $this->user_model->get_all_user();
        $data['activeuser']= $this->user_model->get_all_active_user();

        $data['account_name']= $this->session->userdata('account_name');;

        $this->template->load('user/admin', $views, $data);

    }
    
    /**
     * Logout
     */
    public function logout(){
        $success = $this->acl_auth->logout(true);
        
        if ($success){
            $this->redirect('login');
        }else{
            $this->redirect('lists');
        }
    }// logout()

    /**
     * Testing action
     * 
     */
    public function time(){
        $data=array('time'=>0, 'date'=>'');
        $time=time();
        $data['time']=$this->input->post('time')/1000;
        $data['servertime']=  $time;
        $data['date']=  date('Y-m-d H:i:s', $data['time']);
        $data['serverdate']=  date('Y-m-d H:i:s', $time);
        $data['timediff']=  $time-$data['time'];
        $data['ini.timezone']=  ini_get('date.timezone');
        $data['default.timezone']=  date_default_timezone_get();
        $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($data));
        
    }// logout()
    
    protected function redirect($path)
    {
        redirect('admin/'.$path);
    }
    
} // User class
